<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.semester" placeholder="学期" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in semesterOption" :key="key" :label="value" :value="key" />
      </el-select>
      <SearchOptionCourse :course-id="listQuery.course_id" style="width: 180px" @setSearchCourseId="searchCourseId" />
      <SearchOptionClass :class-id="listQuery.class_ids" style="width: 180px" @setSearchClassId="searchClassId" />
      <!--      <SearchOptionRoom :room-id="listQuery.class_room_id" style="width: 180px" @setSearchRoomId="searchRoomId" />-->
      <!--      <SearchOptionUser :type="listQuery.teacher_ids" style="width: 180px" @setSearchUserId="searchUserId" />-->
      <div class="filter-item">
        <el-date-picker
          v-model="listQuery.stime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </div>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" align="center">
        <template slot-scope="{row}">
          <el-link @click="jumpDetail(row.id)">{{ row.courseInfo.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="授课老师" align="center">
        <template slot-scope="{row}">
          <p v-for="(item,index) in row.teacherInfo" :key="index" style="margin:0">{{ item }}</p>
        </template>
      </el-table-column>
      <el-table-column label="课号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.course_number }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上课班级" align="center">
        <template slot-scope="{row}">
          <p v-for="(item,index) in row.schoolClassInfo" :key="index" style="margin:0">{{ item.name }}</p>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" width="90">
        <template slot-scope="{row}">
          <span>{{ shortTime(row.stime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" width="90">
        <template slot-scope="{row}">
          <span>{{ shortTime(row.etime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学期" prop="semester" align="center" sortable="custom" :class-name="getSortClass('semester')">
        <template slot-scope="{row}">
          <span>{{ semesterOption[row.semester] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="教室名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.classRoomInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出席人员" align="center" width="100">
        <template slot-scope="{row}">
          <el-link @click="jumpDetailUser(row.id)">{{ row.timetableUserInfo[1] }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="分组管理" align="center">
        <template slot-scope="{row}">
          <el-link @click="jumpDetailGroup(row.id)">{{ groupOption[row.is_group_open] }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="排座管理" align="center">
        <template slot-scope="{row}">
          <el-link @click="jumpDetailSeat(row.id)">{{ seatOption[row.is_seat_open] }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="考勤" align="center">
        <template slot-scope="{row}">
          <img src="../../assets/icon/kqtj.png" alt="" @click="jumpDetailKaoqin(row.id)">
        </template>
      </el-table-column>
      <el-table-column label="上课教室" align="center">
        <template slot-scope="{row}">
          <span>{{ row.classRoomSeatInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item label="课程名称" prop="course_id">
          <el-select v-model="temp.course_id" class="filter-item" filterable>
            <el-option v-for="(value,key) in courseList" :key="key" :label="value.name" :value="value.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="上课班级" prop="class_ids">
          <!-- <el-input v-model="temp.class_ids" /> -->
          <el-select v-model="temp.class_ids" class="filter-item" multiple filterable>
            <el-option v-for="(value,key) in classList" :key="key" :label="value.name" :value="value.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="教室名称" prop="class_room_id">
          <el-select v-model="temp.class_room_id" class="filter-item" filterable>
            <el-option v-for="(value,key) in roomList" :key="key" :label="value.name" :value="value.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="授课老师" prop="teacher_ids">
          <el-select v-model="temp.teacher_ids" prop="semester" class="filter-item" multiple filterable>
            <el-option v-for="(value,key) in teacherList" :key="key" :label="value.name" :value="value.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="学期">
          <el-select v-model="temp.semester" prop="semester" class="filter-item">
            <el-option v-for="(value,key) in semesterOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="stime">
          <div class="block">
            <el-date-picker
              v-model="temp.stime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="开始日期"
            />
          </div>
        </el-form-item>
        <el-form-item label="结束日期" prop="etime">
          <div class="block">
            <el-date-picker
              v-model="temp.etime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="结束日期"
            />
          </div>
        </el-form-item>
        <el-form-item label="上课教室" prop="class_room_seat_id">
          <el-select v-model="temp.class_room_seat_id" class="filter-item" filterable>
            <el-option v-for="(value,key) in roomSeatList" :key="key" :label="value.name " :value="value.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="课号">
          <el-input v-model="temp.course_number" />
        </el-form-item>
        <el-form-item label="课程简称">
          <el-input v-model="temp.short_name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { userPage } from '@/api/user'
import { classPage, classRoomPage, classRoomSeatPage } from '@/api/class'
import SearchOptionCourse from '@/components/SearchOption/course'
import SearchOptionClass from '@/components/SearchOption/class'
import { courseTimetablePage, courseTimetableUpdate, courseTimetableDelete, coursePage } from '@/api/course'
import waves from '@/directive/waves' // waves directive
import { notifySuccess, formatJson, my_confirm, listQueryFilter } from '@/utils/tool'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'CourseTimetablePage',
  components: { Pagination, SearchOptionCourse, SearchOptionClass },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        number: undefined,
        stime: ''
      },
      semesterOption: { 1: '第一学期', 2: '第二学期', 3: '第三学期', 4: '第四学期' },
      groupOption: { 0: '未分组', 1: '已发布' },
      seatOption: { 0: '未排座', 1: '已发布' },
      usertypeOptions: { 1: '学生', 2: '班级主管', 3: '其他' },
      temp: {
        id: undefined,
        course_id: '',
        courseInfo: {},
        classRoomInfo: {},
        schoolClassInfo: [],
        class_ids: [],
        class_room_id: '',
        teacher_ids: '',
        semester: '',
        class_room_seat_id: '',
        course_number: '',
        short_name: '',
        stime: '',
        etime: '',
        is_group_open: '',
        is_seat_open: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        teacher_ids: [{ required: true, message: '教师必选', trigger: 'change' }],
        class_ids: [{ required: true, message: '班级必选', trigger: 'change' }]
      },
      downloadLoading: false,
      classListQuery: {
        page: 1,
        limit: 1000,
        year: undefined,
        quarter: undefined,
        semester: undefined,
        name: undefined,
        is_show: undefined,
        type: undefined
      },
      teacherListQuery: {
        page: 1,
        limit: 1000,
        type: 1,
        name: undefined,
        number: undefined
      },
      roomListQuery: {
        page: 1,
        limit: 1000
      },
      courseListQuery: {
        page: 1,
        limit: 1000
      },
      roomSeatListQuery: {
        page: 1,
        limit: 1000
      },
      courseList: [],
      roomList: [],
      roomSeatList: [],
      classList: [],
      teacherList: [],
      selectedClass: [],
      selectedTeacher: [],
      selectedCourse: [],
      selectedRoom: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 请求上课教室接口
    getRoomSeatList() {
      classRoomSeatPage(this.roomSeatListQuery).then(response => {
        this.roomSeatList = response.data
      })
    },
    getCourseList() {
      this.courseListQuery = listQueryFilter(this.courseListQuery)
      coursePage(this.courseListQuery).then(response => {
        this.courseList = response.data
      })
    },
    getRoomList() {
      this.roomListQuery = listQueryFilter(this.roomListQuery)
      classRoomPage(this.roomListQuery).then(response => {
        this.roomList = response.data
      })
    },
    getTeacherList() {
      this.teacherListQuery = listQueryFilter(this.teacherListQuery)
      userPage(this.teacherListQuery).then(response => {
        this.teacherList = response.data
      })
    },
    getClassList() {
      this.classListQuery = listQueryFilter(this.classListQuery)
      classPage(this.classListQuery).then(response => {
        this.classList = response.data
      })
    },
    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      courseTimetablePage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    jumpDetail(id) {
      this.$router.push({
        path: '/course/timetableDetail',
        query: {
          id: id,
          tab: 'first'
        }
      })
    },
    jumpDetailUser(id) {
      this.$router.push({
        path: '/course/timetableDetail',
        query: {
          id: id,
          tab: 'first'
        }
      })
    },
    jumpDetailGroup(id) {
      this.$router.push({
        path: '/course/timetableDetail',
        query: {
          id: id,
          tab: 'second'
        }
      })
    },
    jumpDetailSeat(id) {
      this.$router.push({
        path: '/course/timetableDetail',
        query: {
          id: id,
          tab: 'third'
        }
      })
    },
    jumpDetailKaoqin(id) {
      this.$router.push({
        path: '/course/timetableDetail',
        query: {
          id: id,
          tab: 'fifth'
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'sort') {
        this.sortByID(order, prop)
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.listQuery.querySort = '+' + prop
      } else {
        this.listQuery.querySort = '-' + prop
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        course_id: '',
        courseInfo: {},
        classRoomInfo: {},
        class_ids: [],
        class_room_id: '',
        teacher_ids: '',
        semester: '',
        course_number: '',
        short_name: ''
      }
    },
    handleCreate() {
      this.getRoomSeatList()
      this.getRoomList()
      this.getCourseList()
      this.getClassList()
      this.getTeacherList()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const creatTempData = JSON.parse(JSON.stringify(this.temp))
          creatTempData.class_ids.push(' ')
          creatTempData.class_ids.unshift(' ')
          creatTempData.class_ids = creatTempData.class_ids.join(',')
          creatTempData.class_ids = creatTempData.class_ids.replace(/ /g, '')
          creatTempData.teacher_ids.push(' ')
          creatTempData.teacher_ids.unshift(' ')
          creatTempData.teacher_ids = creatTempData.teacher_ids.join(',')
          creatTempData.teacher_ids = creatTempData.teacher_ids.replace(/ /g, '')
          delete creatTempData.classRoomInfo
          delete creatTempData.courseInfo
          delete creatTempData.classRoomSeatInfo

          courseTimetableUpdate(creatTempData).then(() => {
            this.list.unshift(creatTempData)
            this.dialogFormVisible = false
            this.getList()
            notifySuccess(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.getRoomSeatList()
      this.getRoomList()
      this.getCourseList()
      this.getClassList()
      this.getTeacherList()
      this.temp = Object.assign({}, row)
      this.temp.class_ids = row.class_ids.split(',').filter(item => { return item })
      this.temp.teacher_ids = row.teacher_ids.split(',').filter(item => { return item })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = JSON.parse(JSON.stringify(this.temp))
          tempData.class_ids.push(' ')
          tempData.class_ids.unshift(' ')
          tempData.class_ids = tempData.class_ids.join(',')
          tempData.class_ids = tempData.class_ids.replace(/ /g, '')
          tempData.teacher_ids.push(' ')
          tempData.teacher_ids.unshift(' ')
          tempData.teacher_ids = tempData.teacher_ids.join(',')
          tempData.teacher_ids = tempData.teacher_ids.replace(/ /g, '')
          delete tempData.classRoomInfo
          delete tempData.timetableUserInfo
          delete tempData.courseInfo
          delete tempData.schoolClassInfo
          delete tempData.teacherInfo
          delete tempData.classRoomSeatInfo
          courseTimetableUpdate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        courseTimetableDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['课程名称', '班级名称', '教师名称', '教室名称']
        const filterVal = ['course_id', 'class_ids', 'teacher_ids', 'class_room_id']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '课程的课表'
        })
        this.downloadLoading = false
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    shortTime: function(time) {
      return time.substring(0, 10)
    },
    searchCourseId: function(data) {
      this.listQuery.course_id = data.courseId
    },
    searchRoomId: function(data) {
      this.listQuery.class_room_id = data.roomId
    },
    searchClassId: function(data) {
      this.listQuery.class_ids = data.classId
    },
    searchUserId: function(data) {
      this.listQuery.teacher_ids = data.userId
    }
  }
}
</script>
